<template>
  <div ref="chartRef" :style="{
    width: ' 100 %',
    height: proxy.$size(height, '320px'),
  }">
  </div>
</template>
<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, getCurrentInstance, onUnmounted } from 'vue';
const { proxy } = getCurrentInstance() as any;
const props = withDefaults(
  defineProps<{
    data?: any;
    height?: string | number;
    dayName?: string;
    seriesSet?: any;//数据设置
  }>(),
  {
    data: [],
    dayName: 'day',
    seriesSet: [
      {
        type: 'visits',
        name: '点击量',
      }
    ],
  },
);
// 获取 DOM 元素的引用
const chartRef = ref<HTMLDivElement | null>(null);
let chartInstance: echarts.ECharts | null = null;
const setOption = () => {

}
const getArr = (keyName: string, arr: any[] = props.data) => {
  return arr.map((el: any) => el[keyName])
}
onMounted(() => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
    // 定义图表的配置项和数据
    const option = {
      legend: {
        data: props.seriesSet.length > 1 ? getArr('name', props.seriesSet) : []
      },
      //开启提示
      tooltip: {
        trigger: 'axis'
      },
      //画图布局
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: props.seriesSet.length > 1 ? '12%' : '6%',
        containLabel: true
      },
      //x轴数据
      xAxis: {
        type: 'category',
        boundaryGap: true,
        data: getArr(proxy.dayName)
      },
      //y轴数据
      yAxis: {
        type: 'value'
      },
      series: props.seriesSet.map((row: any) => ({
        type: 'line',
        ...row,
        stack: 'Total',
        data: getArr(row.key),
      })),
    };
    // 使用配置项和数据显示图表
    option && chartInstance.setOption(option);
  }
  // 监听窗口大小变化并调整图表大小
  window.addEventListener('resize', handleResize);
});
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};
onUnmounted(() => {
  // 清理事件监听器
  window.removeEventListener('resize', handleResize);
  // 销毁图表实例
  if (chartInstance) {
    chartInstance.dispose();
  }
});
</script>
<style scoped lang="scss"></style>
